<?php

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name)
            return $name;
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }

}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++)
            $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }

}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }

}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }

}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $url = preg_match("/^https?:\/\/(.*)/i", $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
            if (is_bool($domain)) {
                $public = \think\Config::get('view_replace_str.__PUBLIC__');
                $url = rtrim($public, '/') . $url;
                if (!preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
                    $url = request()->domain() . $url;
                }
            } else {
                $url = $domain . $url;
            }
        }
        return $url;
    }

}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === FALSE) {
                return FALSE;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return TRUE;
        } elseif (!is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) {
            return FALSE;
        }
        fclose($fp);
        return TRUE;
    }

}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname))
            return false;
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }

}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }

}

if (!function_exists('mb_ucfirst')) {

    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }

}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields)
            return $items;
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }

}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, TRUE);
        }
    }

}


/**
 * 多个数组的笛卡尔积
 * @param unknown_type $data
 * @return array
 */
function combineDika() {
    $data = func_get_args();
    $data = current($data);
    $cnt = count($data);
    $result = array();
    $arr1 = array_shift($data);
    foreach($arr1 as $key=>$item)
    {
        $result[] = array($item);
    }
    
    foreach($data as $key=>$item)
    {
        $result = combineArray($result,$item);
    }
    return $result;
}


/**
 * 两个数组的笛卡尔积
 * @param unknown_type $arr1
 * @param unknown_type $arr2
 */
function combineArray($arr1,$arr2) {
    $result = array();
    foreach ($arr1 as $item1)
    {
        foreach ($arr2 as $item2)
        {
            $temp = $item1;
            $temp[] = $item2;
            $result[] = $temp;
        }
    }
    return $result;
}

/**
 * curl获取信息
 * @param $url //URL地址
 * @param string $type //传输类型 默认get, post
 * @param string $postData //post的数据
 * @param int $time //超时时间
 * @return mixed
 */
function curlGetInfo($url, $type="get", $postData = '', $time = 30, $json=true, $header = []){
    if($url == ''){
        return false;
    }
    
    $ch = curl_init((string)$url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    if($type == 'post'){
        curl_setopt($ch, CURLOPT_POST,true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
    curl_setopt($ch, CURLOPT_TIMEOUT,(int)$time);
    if($header) {
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if($err){
        $returnData =  array(
            'status' => false,
            'info' => "cURL Error #:" . $err
        );
    } else {
	    $returnData = $json ? json_decode($res, true): $res;
    }
    return $returnData;
}

if(!function_exists('load_wec'))
{
    /**
     * 获取微信操作对象
     * @param string $type
     * @param array $config
     * @return \Wechat\Receive|\Wechat\User|\Wechat\Pay|\Wechat\Script|\Wechat\Oauth|\Wechat\Menu|\Wechat\Media|\Wechat\Card|\Wechat\Custom|\Wechat\Limit|\Wechat\Product|\Wechat\Qrcode|\Wechat\Scan|\Wechat\Shake|\Wechat\Tags|\Wechat\Template|\Wechat\Wifi|\WeMini\Crypt|\WeMini\Qrcode|\WeMini\Plugs|\WeMini\Poi|\WeMini\Template|\WeMini\Total
     */
    function load_wec($type = 'Pay',$config=[],$namespace='WeChat')
    {
        static $wechat = [];
        $classname = '\\'.$namespace.'\\'.$type;
        $index = md5(strtolower($classname));
        if (!isset($wechat[$index])) {
            $file = VENDOR_PATH.'WeChat/include.php';
            if(!file_exists($file))
            {
                return null;
            }
            require_once($file);
            $wechat[$index] = new $classname($config);
        }
        return $wechat[$index];
    }

}


if(!function_exists('load_tool'))
{
    /**
     * 获取Tools操作对象
     * @param string $cache_path
     * @return WeChat\Contracts\Tools
     */
    function load_tool($cache_path='')
    {
        static $tools = [];
        $index = md5(strtolower('tools'));
        if (!isset($tools[$index])) {
            $file = VENDOR_PATH.'Wechat/include.php';
            if(!file_exists($file))
            {
                return null;
            }
            require_once($file);
            $tool = new \WeChat\Contracts\Tools();
            $tool::$cache_path=$cache_path;
            $tools[$index] = $tool;
        }
        return $tools[$index];
    }

}


if(!function_exists('load_ali'))
{
    /**
     * 获取支付宝操作对象
     * @param string $classname
     * @return \AopClient
     */
    function load_ali($classname="AopClient")
    {
        static $alipay = [];
        $index = md5(strtolower($classname));
        if (!isset($alipay[$index])) {
            $file = VENDOR_PATH.'alipay/aop/AopClient.php';
            if(!file_exists($file))
            {
                return null;
            }
            require_once($file);
            $alipay[$index] = new $classname();
        }
        return $alipay[$index];
    }

}


if(!function_exists('load_top'))
{
    /**
     * 获取微信操作对象
     * @param string $appKey
     * @param string $secret
     * @return \TopClient
     */
    function load_top($appKey  , $secret)
    {
        static $topsdk = [];
        $index = md5(strtolower('TopClient'));
        if (!isset($topsdk[$index])) {
            $file = VENDOR_PATH.'taobao/TopSdk.php';
            if(!file_exists($file))
            {
                return null;
            }
            require_once($file);
            $topsdk[$index] = new \TopClient($appKey,$secret);
        }
        return $topsdk[$index];
    }

}



if(!function_exists('load_tbk_req'))
{
    /**
     * 获取微信操作对象
     * @param string $class
     * @param string $adZoneId
     * @param int $platForm
     * @return \TbkDgItemCouponGetRequest|\TbkCouponGetRequest
     */
    function load_tbk_req($class , $adZoneId='' , $platForm = 0)
    {
        static $topsdk = [];
        $index = md5(strtolower($class));
        if (!isset($topsdk[$index])) {
            $file = VENDOR_PATH.'taobao/TopSdk.php';
            if(!file_exists($file))
            {
                return null;
            }
            require_once($file);
            $classname = '\\'.$class.'Request';
            $req = new $classname();
            if($adZoneId)
            {
                $req->setAdzoneId($adZoneId);
            }
            if($platForm)
            {
                $req->setPlatform($adZoneId);
            }
            $topsdk[$index] = $req;
        }
        return $topsdk[$index];
    }

}

/***
 * 上传图片
 * @param $imgName
 * @param string $dir
 * @param array $extion
 * @return array
 */
function uploadImg($imgName, $dir='', $extion=['ext'=>'jpg,png,gif,jpeg']){
    $file = request()->file($imgName);
    $msg = '文件不存在';
    if($file){
        $savedir = 'public' . DS . 'uploads'.DS.$dir;
        $info = $file->validate($extion)->move(ROOT_PATH . $savedir);
        if($info){
            $path = 'uploads'.DS.$dir.DS.$info->getSaveName();
            return [
                'status' => true,
                'path' => $path,
            ];
        }else{
            $msg = '上传图片出错：'.$file->getError();
        }
    }
    return [
        'status' => false,
        'msg' => $msg,
    ];
}


function delLog($path, $number = 10){
	$dirHandle = opendir($path);
	while(!$file = readdir($dirHandle)) {
		if($file == '..' || $file == '..') {
			continue;
		}
		
		if(is_dir($file)) {
			delLog($path.DS.$file);
		}
		
		
	}
	closedir($dirHandle);
}

/**
 * 取汉字的第一个字的首字母
 * @param type $str
 * @return string|null
 */
function _getFirstCharter($str){
	if(empty($str)){return '';}
	$fchar=ord($str{0});
	if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
	$s1=iconv('UTF-8','gb2312',$str);
	$s2=iconv('gb2312','UTF-8',$s1);
	$s=$s2==$str?$s1:$str;
	$asc=ord($s{0})*256+ord($s{1})-65536;
	if($asc>=-20319&&$asc<=-20284) return 'A';
	if($asc>=-20283&&$asc<=-19776) return 'B';
	if($asc>=-19775&&$asc<=-19219) return 'C';
	if($asc>=-19218&&$asc<=-18711) return 'D';
	if($asc>=-18710&&$asc<=-18527) return 'E';
	if($asc>=-18526&&$asc<=-18240) return 'F';
	if($asc>=-18239&&$asc<=-17923) return 'G';
	if($asc>=-17922&&$asc<=-17418) return 'H';
	if($asc>=-17417&&$asc<=-16475) return 'J';
	if($asc>=-16474&&$asc<=-16213) return 'K';
	if($asc>=-16212&&$asc<=-15641) return 'L';
	if($asc>=-15640&&$asc<=-15166) return 'M';
	if($asc>=-15165&&$asc<=-14923) return 'N';
	if($asc>=-14922&&$asc<=-14915) return 'O';
	if($asc>=-14914&&$asc<=-14631) return 'P';
	if($asc>=-14630&&$asc<=-14150) return 'Q';
	if($asc>=-14149&&$asc<=-14091) return 'R';
	if($asc>=-14090&&$asc<=-13319) return 'S';
	if($asc>=-13318&&$asc<=-12839) return 'T';
	if($asc>=-12838&&$asc<=-12557) return 'W';
	if($asc>=-12556&&$asc<=-11848) return 'X';
	if($asc>=-11847&&$asc<=-11056) return 'Y';
	if($asc>=-11055&&$asc<=-10247) return 'Z';
	return null;
}

/**
 * 首字母排序
 * @param $arr 要排序的数组
 * @param $key 要排序的键名
 * @return mixed
 */
function firstLetterSort($arr, $key) {
	$settlesRes = array();
	foreach ($arr as $sett) {
		$sname = $sett[$key];
		$snameFirstChar = _getFirstCharter($sname); //取出门店的第一个汉字的首字母
		$settlesRes[] = $snameFirstChar;//以这个首字母作为key
	}
	sort($settlesRes);
	array_multisort($settlesRes, SORT_ASC, $arr);
	return $arr;
	
}


/**
 * 递归目录下的文件
 * @param $arr_file
 * @param $directory
 */
function readDirFile(&$arr_file, $directory)
{
	
	$mydir = dir($directory);
	while($file = $mydir->read())
	{
		if($file == '.' || $file == '..') {
			continue;
		}
		
		$path = $directory.DS.$file;
		if(is_dir($path)) {
			readDirFile($arr_file, $path);
		} else {
			$arr_file[] = $path;
		}
	}
	$mydir->close();
}

